package org.lanettiesso.dubbo.simple.registry;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MemoryRegistryCenter {

    private final static List<Class<?>> CONSUMERS = new ArrayList<>();

    private final static Map<Class<?>, Object> CLAZZ_BEAN_MAP = new HashMap<>();

    public static void registryConsumerClazz(Class<?> clazz) {
        CONSUMERS.add(clazz);
    }

    public static void registryProvider(Class<?> clazz, Object o) {
        for (Class<?> clz : CONSUMERS) {
            Class<?>[] interfaces = clazz.getInterfaces();
            for (Class<?> anInterface : interfaces) {
                if (anInterface.equals(clz)) {
                    CLAZZ_BEAN_MAP.put(clz, o);
                    return;
                }
            }
        }
    }

    public static Object invoke(Class<?> clazz, String methodName, Object... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method;
        if (args == null) {
            method = clazz.getDeclaredMethod(methodName);
        } else {
            Class<?>[] classes = new Class[args.length];
            for (int i = 0, classesLength = classes.length; i < classesLength; i++) {
                classes[i] = args[i].getClass();
            }
            method = clazz.getDeclaredMethod(methodName, classes);
        }

        return method.invoke(CLAZZ_BEAN_MAP.get(clazz), args);
    }


}
